﻿using KD.DLPRO.NewPlug;
using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Log;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.ServiceHelper.Excel;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.Client;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;


namespace kingdee.scm.banqiao.csv
{
    public class POCsvImport : AbstractBillPlugIn
    {
        public override void EntryBarItemClick(BarItemClickEventArgs e)
        {
            if (e.BarItemKey.ToUpper().Equals("TBIMPORT"))
            {
                Logger.Info("", "采购入库单导入表单插件");
                DynamicFormShowParameter showParam = new DynamicFormShowParameter();
                showParam.FormId = "BGP_IMPORTCGMX";
                this.View.ShowForm(showParam,
                    new Action<FormResult>((formResult) =>
                    {
                        if (formResult != null && formResult.ReturnData != null)
                        {
                            string fullFileName = formResult.ReturnData.ToString();
                            Logger.Info("", string.Format("fullFileName:{0}.", fullFileName));
                            this.DoImportEntry(fullFileName);
                        }
                    }));
            }
        }


        private void DoImportEntry(string fullFileName)
        {
            try
            {
                {
                    {
                        Logger.Info("", "开始导入.");
                        //  读csv文件并提取批号等
                        POCsvImportModel pOCsvImportModel = new POCsvImportModel(fullFileName);

                        //  查询所有pn对应的number
                        DateTime queryStartTime = DateTime.Now;
                        Dictionary<String, String> pnAndNumberMap = this.GetWlOrmByPn(pOCsvImportModel.pns);
                        DateTime pnQueryTime = DateTime.Now;
                        Logger.Info("", string.Format("物料表通过pn取物料内码 时间差:{0}", (pnQueryTime - queryStartTime).TotalSeconds));

                        //  通过批号查询数据库中的lot
                        Dictionary<String, String> lotsMap = this.getLotMapFromDB(pOCsvImportModel.lots);
                        DateTime lotQueryTime = DateTime.Now;
                        Logger.Info("", string.Format("通过批号查询数据库中的lot 时间差:{0}", (lotQueryTime - pnQueryTime).TotalSeconds));

                        // 创建导入单据
                        this.generateBill(pOCsvImportModel.dt, pnAndNumberMap, lotsMap);
                        Logger.Info("", "导入结束.");
                        this.View.UpdateView("FInStockEntry");
                        this.View.ShowMessage("导入成功.");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new KDBusinessException("", ex.Message);
            }
        }

        /// <summary>
        /// 创建导入单据
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="pnAndNumberMap"></param>
        /// <param name="lotsMap"></param>
        private void generateBill(DataTable dt, Dictionary<String, String> pnAndNumberMap, Dictionary<String, String> lotsMap) {
            Entity entity = this.View.BusinessInfo.GetEntity("FInStockEntry");
            int index = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dataRow = dt.Rows[i];
                Logger.Info("", string.Format("开始处理第{0}行数据.", i));
                string pn = dataRow[1].ToString();

                pn = pn.Substring(10, 5);
                Logger.Info("", string.Format("截取后pn码:{0}.", pn));

                //  pnAndNumberMap存在
                if (pnAndNumberMap.ContainsKey(pn))
                {
                    string wlNum = pnAndNumberMap[pn];
                    this.Model.SetItemValueByNumber("FMaterialId", wlNum, index);
                }

                this.View.InvokeFieldUpdateService("FMaterialId", index);

                this.View.Model.SetValue("FRealQty", 1, index);
                this.View.InvokeFieldUpdateService("FRealQty", index);

                this.View.Model.SetValue("FStockId_Id", 111286, index);

                this.View.Model.SetValue("F_BGP_order", dataRow[0].ToString(), index);
                this.View.Model.SetValue("F_BGP_AWB", dataRow[3].ToString(), index);

                //DateTime n4 = DateTime.Now;
                // 批号处理
                string lot = dataRow[5].ToString();
                if (lotsMap.ContainsKey(lot))
                {
                    String llot = lotsMap[lot];
                    string ss = llot + lot;
                    Logger.Info("", string.Format("批号:{0},调整后批号:{1}.", lot, ss));
                    this.View.Model.SetValue("FLot", ss, index);
                    this.View.Model.SetValue("F_OPA_LOT", ss, index);
                }
                else {
                    string ss = lot;
                    this.View.Model.SetValue("FLot", ss, index);
                    this.View.Model.SetValue("F_OPA_LOT", ss, index);
                }


                this.View.Model.SetValue("FBarCodeOkClasses", dataRow[1].ToString(), index);
                this.View.Model.SetValue("FProduceDate", dataRow[4].ToString(), index);
                this.View.InvokeFieldUpdateService("FProduceDate", index);
                string key3 = string.Format("$${0}__{1}", "FAuxPropId", "FF100009");
                string value3 = decimal.Parse(dataRow[6].ToString()).ToString("0.00");
                this.Model.SetValue(key3, value3, index);

                string key4 = string.Format("$${0}__{1}", "FAuxPropId", "FF100008");
                string value4 = decimal.Parse(dataRow[7].ToString()).ToString("0.00");
                this.Model.SetValue(key4, value4, index);

                string key5 = string.Format("$${0}__{1}", "FAuxPropId", "FF100002");
                string value5 = decimal.Parse(dataRow[8].ToString()).ToString("0.00");
                this.Model.SetValue(key5, value5, index);
                string key6 = string.Format("$${0}__{1}", "FAuxPropId", "FF100004");
                string value6 = decimal.Parse(dataRow[9].ToString()).ToString("0.00");
                this.Model.SetValue(key6, value6, index);

                string key7 = string.Format("$${0}__{1}", "FAuxPropId", "FF100005");
                string value7 = decimal.Parse(dataRow[10].ToString()).ToString("0.00");
                this.Model.SetValue(key7, value7, index);
                index++;
                this.Model.CreateNewEntryRow(entity, index);
            }
        }

        /// <summary>
        /// 物料表通过pn取物料内码
        /// </summary>
        /// <param name="pns"></param>
        /// <returns></returns>
        private Dictionary<String, String> GetWlOrmByPn(List<string> pns)
        {
            String pn = string.Join("','", pns.ToArray());
            List<DynamicObject> dynamicObjects =
                BusinessDataServiceHelper
                    .Load(this.Context, "BD_MATERIAL", null, OQLFilter.CreateHeadEntityFilter("F_BGP_Text in ('" + pn + "') and FDocumentStatus='C' and FUSEORGID=" + this.Context.CurrentOrganizationInfo.ID + ""))
                    .ToList<DynamicObject>();

            Dictionary<String, String> pnAndNumber = new Dictionary<string, string>();
            foreach (DynamicObject wlOrm in dynamicObjects)
            {
                if (null != wlOrm)
                {
                    pnAndNumber.Add(wlOrm["F_BGP_Text"].ToString(), wlOrm["Number"].ToString());
                }
            }

            return pnAndNumber;
        }

        /// <summary>
        /// 通过批号查询数据库中的lot
        /// </summary>
        /// <param name="lots"></param>
        /// <returns></returns>
        public Dictionary<String, String> getLotMapFromDB(List<String> lots) {
            //string sql = "SELECT top 1 FNUMBER FROM T_BD_LOTMASTER WHERE FLOTSTATUS=1 and FCANCELSTATUS='A' and FNUMBER LIKE '%" + lot + "' order by fnumber";
            String lots_str = string.Join("','", lots.ToArray());
            string sql = "select FNUMBER ,count(FNUMBER) as FNUMBERCOUNT\n" +
                    "from T_BD_LOTMASTER where FLOTSTATUS=1 and FCANCELSTATUS='A' and\n" +
                    "FNUMBER in ('" + lots_str + "') \n" +
                    "--Collate Chinese_Prc_CS_AI\n" +
                    "group by fnumber\n";

            Dictionary<string, int> fnumberCountMap = new Dictionary<string, int>();
            using (IDataReader reader = DBUtils.ExecuteReader(this.Context, sql))
            {
                while (reader.Read()) {
                    //  查询出来的FNUMBER
                    string lotfirst = reader[0].ToString();
                    int lotcount = int.Parse(reader[1].ToString());
                    fnumberCountMap.Add(lotfirst, lotcount);
                }
                reader.Close();
            };
            //DateTime n5 = DateTime.Now;
            //Logger.Info("", string.Format("时间差:{0},总时间差:{1}.", (n5 - n4).TotalSeconds, (n5 - n1).TotalSeconds));

            Dictionary<String, String> lotMap = new Dictionary<string, string>();

            foreach (String lot in lots)
            {
                //  根据数量匹配，加空格
                if (fnumberCountMap.ContainsKey(lot)) {
                    string llot = "";
                    for (int i1 = 0; i1 < fnumberCountMap[lot]; i1++)
                    {
                        llot += " ";
                    }
                    lotMap.Add(lot, llot);
                }
                else {
                    lotMap.Add(lot, "");
                }
            }

            return lotMap;
        }
    }

    /// <summary>
    /// 采购订单导入model类
    /// </summary>
    class POCsvImportModel{
        public DataTable dt { get; set; }
        public List<String> pns { get; set; }
        public List<String> lots { get; set; }

        /// <summary>
        /// 读取csv文件，并遍历取得pn和lot
        /// </summary>
        /// <param name="fullFileName"></param>
        public POCsvImportModel(String fullFileName) {
            CsvStreamReader csv = new CsvStreamReader(fullFileName);
            this.dt = csv[1];
            Logger.Info("", string.Format("CSV数量:{0}.", dt.Rows.Count));

            // 第一遍for，取string pn = dt.Rows[i][1].ToString()，list
            // 批量调用BusinessDataServiceHelper.Load(this.Context, "BD_MATERIAL", null, OQLFilter.CreateHeadEntityFilter("F_BGP_Text='" + pn + "' and FDocumentStatus='C' and FUSEORGID=" + this.Context.CurrentOrganizationInfo.ID + ""))
            // 返回dictionary，Key：pn，Value：string wlNum = wlOrm["Number"].ToString()

            //  循环获取csv文件中的所有pn
            //  循环获取csv文件中的所有lot
            this.pns = new List<string>();
            this.lots = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string pn = dt.Rows[i][1].ToString();

                pn = pn.Substring(10, 5);
                pns.Add(pn);

                //  lot
                string lot = dt.Rows[i][5].ToString();
                lots.Add(lot);
            }
        }
    }
}
